package com.cheetah.start.module.system.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.cheetah.start.common.config.property.AliYunOssProperty;
import com.cheetah.start.common.enums.FileStatusEnum;
import com.cheetah.start.common.utils.MyFileUtil;
import com.cheetah.start.module.system.domain.SysFile;
import com.cheetah.start.module.system.service.UploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

/**
 * 阿里 oss 上传服务
 *
 * @author xjh
 * @date 2021/12/23
 */
@Service
public class AliOssUploadServiceImpl implements UploadService {
    @Autowired
    private AliYunOssProperty aliYunOssProperty;
    @Value("${spring.application.name}")
    private String appName;

    /**
     * 上传
     *
     * @param file 文件
     * @return {@link String}
     */
    @Override
    public SysFile upload(MultipartFile file) throws IOException {
        String dateFileName = MyFileUtil.getDateFileName(file);

        String proDateFileName = appName + "/" + dateFileName;
        InputStream inputStream = file.getInputStream();
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentType("image/jpg");
        OSS ossClient = new OSSClientBuilder().build(aliYunOssProperty.getEndPoint(), aliYunOssProperty.getAccessKeyId(), aliYunOssProperty.getAccessKeySecret());
        ossClient.putObject(aliYunOssProperty.getBucket(), proDateFileName, inputStream, metadata);
        ossClient.shutdown();

        String host = "https://" + aliYunOssProperty.getBucket() + "." + aliYunOssProperty.getEndPoint() + "/" + proDateFileName;
        SysFile sysFile = new SysFile();
        sysFile.setFileSize((int) (file.getSize() / 1000))
                .setFileName(file.getOriginalFilename())
                .setFilePath(host).setFileNowName(MyFileUtil.getNowName(host))
                .setFileUrl(host).setFileRealPath(host)
                .setCreateTime(new Date())
                .setFileStatus(FileStatusEnum.USE.getCode());
        return sysFile;
    }
}
